/**
 * 登陆状态验证
 * 
 * @author Gill Gong
 */

import React from 'react'
import config from '~/config'
import { Component } from 'react'
import store from '~/common/store'
import modelFactory from '~/models/factory'
import _ from '~/common/underscore-addition'
import { View, Text, Image } from 'react-native'
import SplashScreen from 'react-native-splash-screen'

import App from '~/app'
import Jw from '~/services/jw-inject'
import Login from '~/modules/base/login'

const STATUS = {
  loading: 1,
  login: 2,
  app: 3
}

class MiddleProcess extends Component {
  constructor(ops) {

    super(ops)

    this.navigator = null
    this.state = { status: STATUS.loading }
  }

  render() {

    if(this.state.status === STATUS.loading) {
      
      return this.renderLoading()
    }else if(this.state.status === STATUS.login) {

      return this.renderLogin()
    }else{

      return this.renderApp()
    }
  }

  renderLogin() {

    return <Login onLoginedSuccessHandler={ ()=>this.onLoginedSuccessHandler() } />
  }

  renderApp() {

    return <App />
  }

  renderLoading() {
   
    return (
      <View style={{ height: "100%", display: "flex", justifyContent: "center", alignItems: "center" }}>
        <Image source={ require('~/assets/imgs/logo.png') } />
        <Text style={{ color: "#666", position: "absolute", bottom: 10 }}>杰为软件系统（深圳）有限公司</Text>
      </View>
    )
  }

  onLoginedSuccessHandler() {

    this.appEntryProcess()
  }

  switchToLogin() {

    store.clearToken().then(()=>{

      this.setState({ status: STATUS.login })
    })
  }

  async appEntryProcess() {
    let accessToken = await store.getToken()

    if(_.isEmpty(accessToken)) {
      
      this.setState({ status: STATUS.login })
    }else{
      
      this.checkAccessToken()
    }
  }

  componentDidMount() {
    
    setTimeout(function() {
      SplashScreen.hide()
    }, 1000)
    Jw.gEventBus.on('switchToLogin', ()=>{
      this.switchToLogin()
    })
    this.appEntryProcess()
  }

  checkAccessToken() {
    let accessCheckModel = modelFactory.create({
      method: 'Get',
      externHeaders: { accesstoken: store.getTokenSync() },
      url: `${config.gateway}/authentification-service/authentification/access-token`
    })

    accessCheckModel.exec().then((data)=>{
    
      store.setUser(data)
      this.setState({ status: STATUS.app })
    }).catch(()=>{
      
      this.setState({ status: STATUS.login })
    })
  }
}


export default MiddleProcess
